# Create your views here.

# 导入Django的快捷渲染函数render（替代了手动加载模板和创建HttpResponse）
from django.shortcuts import get_object_or_404, render

# 同样从模型文件导入Question类
from .models import Question
from django.db.models import F
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse

from .models import Choice, Question

# 视图函数定义保持相同
# def index(request):
#     # 数据库查询逻辑完全一致：获取最近发布的5个问题
#     latest_question_list = Question.objects.order_by("-pub_date")[:5]
#
#     # 创建上下文字典的逻辑也相同
#     context = {"latest_question_list": latest_question_list}
#
#     # 使用render快捷函数三合一操作：
#     # 1. 自动加载模板 2. 渲染上下文 3. 返回HttpResponse对象
#     # 参数顺序：请求对象 -> 模板路径 -> 上下文字典
#     return render(request, "polls/index.html", context)
#
# def detail(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, "polls/detail.html", {"question": question})
#
#
# def results(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     return render(request, "polls/results.html", {"question": question})
#
# def vote(request, question_id):
#     question = get_object_or_404(Question, pk=question_id)
#     try:
#         selected_choice = question.choice_set.get(pk=request.POST["choice"])
#     except (KeyError, Choice.DoesNotExist):
#         # Redisplay the question voting form.
#         return render(
#             request,
#             "polls/detail.html",
#             {
#                 "question": question,
#                 "error_message": "You didn't select a choice.",
#             },
#         )
#     else:
#         selected_choice.votes = F("votes") + 1
#         selected_choice.save()
#         # Always return an HttpResponseRedirect after successfully dealing
#         # with POST data. This prevents data from being posted twice if a
#         # user hits the Back button.
#         return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))



from django.db.models import F
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from django.utils import timezone
from .models import Choice, Question
from django.db.models import Sum

class IndexView(generic.ListView):
    template_name = "polls/index.html"
    context_object_name = "latest_question_list"

    def get_queryset(self):
        """Return the last five published questions."""
        return Question.objects.order_by("-pub_date")[:5]


class DetailView(generic.DetailView):
    model = Question
    template_name = "polls/detail.html"

    def get_queryset(self):
        """
        Excludes any questions that aren't published yet.
        """
        return Question.objects.filter(pub_date__lte=timezone.now())

class ResultsView(generic.DetailView):
    model = Question
    template_name = "polls/results.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 获取当前问题的所有选项票数总和
        context['total_votes'] = self.object.choice_set.aggregate(
            total=Sum('votes')
        )['total'] or 0  # 处理无票数的情况
        return context

def vote(request, question_id):
        question = get_object_or_404(Question, pk=question_id)
        try:
            selected_choice = question.choice_set.get(pk=request.POST["choice"])
        except (KeyError, Choice.DoesNotExist):
            # Redisplay the question voting form.
            return render(
                request,
                "polls/detail.html",
                {
                    "question": question,
                    "error_message": "You didn't select a choice.",
                },
            )
        else:
            selected_choice.votes = F("votes") + 1
            selected_choice.save()
            # Always return an HttpResponseRedirect after successfully dealing
            # with POST data. This prevents data from being posted twice if a
            # user hits the Back button.
            return HttpResponseRedirect(reverse("polls:results", args=(question.id,)))


def get_queryset(self):
    """
    Return the last five published questions (not including those set to be
    published in the future).
    """
    return Question.objects.filter(pub_date__lte=timezone.now()).order_by("-pub_date")[
        :5
    ]




# # 导入Django的HttpResponse模块，用于创建HTTP响应对象
# from django.http import HttpResponse
# # 导入Django的模板加载模块，用于加载模板文件
# from django.template import loader
#
# # 从当前目录的models.py文件中导入Question模型
# from .models import Question
#
#
# # 定义名为index的视图函数，所有Django视图都接收HttpRequest对象作为第一个参数
# def index(request):
#     # 从数据库查询最新发布的5个问题，按发布时间倒序排列
#     # 使用order_by("-pub_date")进行降序排序，[:5]切片获取前5条记录
#     latest_question_list = Question.objects.order_by("-pub_date")[:5]
#
#     # 使用Django模板加载器获取位于polls/templates/polls/index.html的模板文件
#     template = loader.get_template("polls/index.html")
#
#     # 创建模板上下文字典，将查询到的问题列表赋值给模板变量latest_question_list
#     context = {
#         "latest_question_list": latest_question_list,
#     }
#
#     # 将上下文数据与请求对象一起渲染模板
#     # 生成渲染后的HTML内容，最后包装成HttpResponse返回给客户端
#     return HttpResponse(template.render(context, request))